package com.ruoyi.web.controller.ora;
import com.google.api.services.androidpublisher.AndroidPublisher;
import com.google.api.services.androidpublisher.model.ProductPurchase;
import com.ruoyi.common.config.GooglePaymentConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.ora.domain.GooglePaymentVerificationResponse;
import com.ruoyi.ora.domain.PaymentVerificationRequest;
import com.ruoyi.ora.service.IGooglePaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;


@RestController
@RequestMapping("/ora/google/payment")
public class GooglePaymentController {
    private static final Logger log = LoggerFactory.getLogger(GooglePaymentController.class);
    private final AndroidPublisher publisher;
    private final GooglePaymentConfig googlePaymentConfig;

    @Resource
    private IGooglePaymentService googlePaymentService;


    // 构造函数注入AndroidPublisher和配置
    public GooglePaymentController(AndroidPublisher publisher, GooglePaymentConfig googlePaymentConfig) {
        this.publisher = publisher;
        this.googlePaymentConfig = googlePaymentConfig;
    }

    /**
     * 验证支付接口
     * @param request 包含订单ID、商品ID和购买令牌的请求体
     * @return 验证结果
     */
    @PostMapping("/verify")
    public AjaxResult verifyPayment(@RequestBody PaymentVerificationRequest request) {
        try {
            // 使用请求参数或配置的默认值
            String packageName = request.getPackageName() != null ? request.getPackageName() : googlePaymentConfig.getPackageName();
            String productId = request.getProductId();
            String purchaseToken = request.getPurchaseToken();
            // 调用Google API验证购买
            GooglePaymentVerificationResponse verification = verifyPurchase(packageName, productId, purchaseToken);
            // 3. 处理验证结果 检查购买状态（0表示购买成功）
            if(verification.isValid()) {
                // 购买成功，更新用户信息
                googlePaymentService.updateUserMembership(request);
                return AjaxResult.success("支付验证成功");
            } else {
                return AjaxResult.error("支付验证失败，购买状态异常");
            }
        } catch (IOException e) {
            return AjaxResult.error("验证支付时发生错误: " + e.getMessage());
        }
    }

    /**
     * 调用Google API验证购买
     * @param packageName
     * @param productId
     * @param purchaseToken
     * @return
     * @throws IOException
     */
    public GooglePaymentVerificationResponse verifyPurchase(String packageName, String productId, String purchaseToken) throws IOException {
        AndroidPublisher.Purchases.Products.Get request = publisher.purchases().products().get(packageName, productId, purchaseToken);
        ProductPurchase purchase = request.execute();
        log.info("调用Google API验证结果：{}",purchase);
        // 5. 返回验证结果
        return new GooglePaymentVerificationResponse(
                purchase.getPurchaseState() == 0, // 0表示支付成功
                purchase.getOrderId(),
                purchase.getPurchaseTimeMillis());
    }

}
